package com.yc.tomcat.impl;

import com.yc.tomcat.*;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class Tomcatimpl implements Tomcat {
    //网站根目录
    public  static final String WEBROOT="E:\\Java三期\\Tomcat\\牛杂小说";
    public static final Map<String,HttpServlet> servletMap=new HashMap<>();
    public static void main(String[] args) throws IOException {
        Tomcatimpl tomcatimpl=new Tomcatimpl();
        tomcatimpl.start(8089);
    }
    @Override
    public void start(int port) throws IOException {

        ServerSocket server = new ServerSocket(port);
        System.out.println("服务器启动成功：" + port);
        while (true) {
            System.out.println("监听浏览器的请求...");
            try (Socket socket = server.accept()) {
                HttpServletRequest request = buildRequest(socket);
                HttpServletResponse response = buildResponse(socket, request);

                //获取请求报文
             /*   InputStream in=socket.getInputStream();
                byte [] bytes=new byte[1024];
                int count=in.read(bytes);
                System.out.println(count);
                System.out.println(new String(bytes,0,count));*/

                //服务器扫描当前工程所有的类 =》 注解 =》 所有的Servlet
                //然后注册Servlet , 默认情况下，servlet应该是在第一次访问时被创建+注册
                servletMap.put("/hello.s", new HelloServlet());
                servletMap.put("/like.s", new LikesServlet());
                servletMap.put("/post.s", new PostServlet());
                servletMap.put("/toindex.s", new RedirectServlet());
                servletMap.put("/cookie.s", new CookieServlet());
                servletMap.put("/addCookie.s", new AddCookieServlet());
                servletMap.put("/login.s", new LoginServlet());
                servletMap.put("/getLoginUser.s", new GetLoginUserServlet());
                servletMap.put("/invalid.s", new InvalidateServlet());


                if (isServletRequest(request)) {
                    processServletRequest(request, response);
                } else if (isStaticRequest(request)) {
                    processStaticRequest(request, response);
                } else {

                    //404 页面
                    // xml 解析错误   ： 格式不佳  告诉浏览器以文本解析数据
                  /*  response.setContentType("text/plain;charset=utf-8");
                    OutputStream out=socket.getOutputStream();
                    out.write("HTTP/1.1 404 error\n".getBytes());
                    //空行
                    out.write("\n".getBytes());
                    //
                    out.write("<h1>404 Error</h1>".getBytes()); // 输出404页面的内容，可以根据需求进行自定义
                    out.close();*/

                }

                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    @Override
    public HttpServletRequest buildRequest(Socket socket) {
        try {
            return new HttpServletRequsetImpl(socket);
        } catch (IOException e) {
           throw new RuntimeException(e);
        }
    }

    @Override
    public HttpServletResponse buildResponse(Socket socket, HttpServletRequest request) {
        return new HttpServletResponseImpl(socket,request);
    }

    @Override
    public boolean isStaticRequest(HttpServletRequest request) {
       String filepath=WEBROOT+request.getRequestURI();
       //判断文件是否存在
        System.out.println( new File(filepath).exists());// 存在是静态资源 不存在是动态资源
        return new File(filepath).exists();
    }

    @Override
    public boolean isServletRequest(HttpServletRequest request) {
        //判断servlet容器中是否含有该请求地址有的话是动态请求

     /*   String[] lines=request.getRequestURI().split("\\?");
        System.out.println(lines[0]);*/
      return servletMap.containsKey(request.getRequestURI());
    }

    @Override
    public boolean processStaticRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //响应 helloworld 页面
        OutputStream out=response.getOutputStream();
        //响应头行
        out.write("HTTP/1.1 200 OK\n".getBytes());
        //空行
        out.write("\n".getBytes());
//        out.write("<h1>hello world<h1>".getBytes());

        String filepath=WEBROOT+request.getRequestURI();
        //从指定的静态资源地址读取指定文件响应给客户端
        try(FileInputStream fis=new FileInputStream(filepath)) {
            byte [] bytes=new byte[1024];
            int count;
            while((count=fis.read(bytes))>0){
                out.write(bytes,0,count);
            }
        }

        return false;
    }

    @Override
    public boolean processServletRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
       /* String[] lines=request.getRequestURI().split("\\?");*/

        //从容器中获取 servlet
        HttpServlet servlet=servletMap.get(request.getRequestURI());
        //由servlet 处理请求，构建响应数据
        servlet.service(request,response);
        //将响应的数据推送给浏览器
        response.flushBuffer();
        return false;
    }

    @Override
    public String getMimeType(String path) {
        return null;
    }

    @Override
    public HttpServlet getServlet(HttpServletRequest request) {
        return null;
    }

    @Override
    public void createSession(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    public void stop() {

    }
}
